import { Request, Response } from "express";
import logger from "../utils/logger-utils";

interface UnifiedResponseBodyParams {
    httpStatus?: number;
    code?: 0 | 1; // 0-成功, 1-失败
    data?: any;
    message: string;
    req: Request;
    res: Response;
}
interface ErrorHandlerParams {
    httpStatus?: number;
    error: any;
    data?: object;
    message: string;
    req: Request;
    res: Response;
}

// 成功返回响应体
export const responseHandler = ({
    httpStatus = 200,
    code: code = 0,
    data: data = {},
    message: message,
    req,
    res,
}: UnifiedResponseBodyParams): void => {
    res.status(httpStatus).json({
        code: code,
        data: data,
        message: message,
    });
    logger.error(`400 || ${res.statusMessage} - ${req.originalUrl} - ${req.method} - ${req.ip}`);
};

// 失败返回响应体
export const errorHandler = ({
    httpStatus = 500,
    message: message,
    data: data = {},
    req,
    res,
}: ErrorHandlerParams): void => {
    responseHandler({
        httpStatus,
        code: 1,
        message: message,
        data: data,
        req,
        res,
    });
};

// 参数错误处理函数
export const paramsHandler = (result: object, req: Request, res: Response) => {
    responseHandler({
        httpStatus: 400,
        code: 1,
        message: "参数错误",
        data: result,
        req,
        res,
    });
};